package com.softer.wxzj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.entity.Page;
import com.softer.wxzj.common.enums.MessageEnum;
import com.softer.wxzj.common.enums.NumStrEnum;
import com.softer.wxzj.common.enums.NumberEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.util.*;
import com.softer.wxzj.entity.*;
import com.softer.wxzj.entity.base.BaseEntity;
import com.softer.wxzj.mapper.*;
import com.softer.wxzj.service.AccKeepAccountService;
import com.softer.wxzj.service.BaseBuildInfoService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * RefReqServiceImpl class
 *
 * @author zcz
 * @date 2019/1/16
 */
@Slf4j
@Service
public class AccKeepAccountServiceImpl implements AccKeepAccountService {
    @Autowired
    AccKeepAccountMapper accKeepAccountMapper;
    @Autowired
    RefReqListMapper refReqListMapper;
    @Autowired
    DepReqMapper depReqMapper;
    @Autowired
    ExpPayReqMapper expPayReqMapper;
    @Autowired
    SysBankOperatorMapper sysBankOperatorMapper;
    @Autowired
    private OperUtil operUtil;
    @Autowired
    private RefPayInfoMapper refPayInfoMapper;
    @Autowired
    private RefReqMapper refReqMapper;
    @Autowired
    AccReverseRecordMapper accReverseRecordMapper;
    @Autowired
    BaseContractorBankInfoMapper baseContractorBankInfoMapper;
    @Autowired
    DepReqListInfoMapper depReqListInfoMapper;
    @Autowired
    BaseHouseInfoMapper baseHouseInfoMapper;
    @Autowired
    ExpPayReqDetailMapper expPayReqDetailMapper;
    @Autowired
    AccTransactionLogMapper accTransactionLogMapper;
    @Autowired
    BaseOwnerInfoMapper baseOwnerInfoMapper;
    @Autowired
    private SysCoreParamMapper sysCoreParamMapper;
    @Autowired
    private ExpProjectReqMapper expProjectReqMapper;
    @Autowired
    private OrgBankInfoMapper orgBankInfoMapper;
    @Autowired
    private BaseBuildInfoMapper baseBuildInfoMapper;
    @Autowired
    private BaseBuildInfoService baseBuildInfoService;
    @Autowired
    private BaseBuildInfoServiceImpl baseBuildInfoServiceImpl;
    @Autowired
    private ExpProjectReqDetailMapper expProjectReqDetailMapper;
    @Autowired
    private AccBusiVouchLinkMapper accBusiVouchLinkMapper;
    @Autowired
    private BaseBankInfoMapper baseBankInfoMapper;
    @Autowired
    private FileServiceImpl fileService;

    @Override
    public CommonResult insert(AccKeepAccount accKeepAccount) {
        return null;
    }

    /**
     * 数据库名称
     *
     * @return
     */
    public String sqlName() {
        String mySqlName = sysCoreParamMapper.getParamValueByCode("57");
        return mySqlName;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult update(AccKeepAccount accKeepAccount) {
        //有效日期
        LocalDate vaildDate;
        //验证日期
        LocalDate verTime = LocalDate.parse(accKeepAccount.getVerificationTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        if (StringUtils.isBlank(accKeepAccount.getVaildDate())) {
            vaildDate = LocalDate.parse("2999-12-12", DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        } else {
            vaildDate = LocalDate.parse(accKeepAccount.getVerificationTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        if (vaildDate.isBefore(verTime)) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "验证日期已过期，有效期截至" + vaildDate);
        }
        accKeepAccount.setAccountState(NumStrEnum.ONE.getNum());
        accKeepAccount.setTallyTime(accKeepAccount.getTallyTime());
        accKeepAccount.setTallyTimeNow(DateUtils.getNow());
        int num = accKeepAccountMapper.update(accKeepAccount);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        accKeepAccount.setBankId(accKeepAccountMapper.getInfo(accKeepAccount.getId()).getBankId());
        accKeepAccount.setBusiNo(accKeepAccountMapper.getInfo(accKeepAccount.getId()).getBusiNo());

        switch (accKeepAccount.getBusiType()) {
            // 记账退款冻结资金减，余额减
            case "310":
                num = changereq(accKeepAccount, NumStrEnum.ONE.getNum(), NumStrEnum.ONE.getNum());
                break;
            // 记账交存冻结资金不动，余额增加
            case "311":
                num = changedep(accKeepAccount, NumStrEnum.ZERO.getNum());
                break;
            //使用
            case "312":
                num = reverseUseSub(accKeepAccount, NumStrEnum.TWO.getNum());
                break;
        }
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        //修改状态
        num = selectAccKeepAccount(accKeepAccount.getBusiType(), accKeepAccount.getId(), NumStrEnum.ZERO.getNum(), NumStrEnum.FOUR.getNum(), NumStrEnum.FOUR.getNum(), NumStrEnum.FIVE.getNum(), NumStrEnum.ONE.getNum(), NumStrEnum.FOUR.getNum());
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        //修改承办银行的金额
        if (accKeepAccount.getBusiType().equals("310") || accKeepAccount.getBusiType().equals("312")) {
            accKeepAccount.setPayAmount(accKeepAccount.getPayAmount().negate());
        }
        //添加到log
        num = intsetLog(accKeepAccountMapper.getInfo(accKeepAccount.getId()));
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        num = accKeepAccountMapper.updateBankMoney(accKeepAccountMapper.getInfo(accKeepAccount.getId()).getBankCode(), accKeepAccount.getPayAmount());
        return CommonResult.ResponseResult(num);
    }

    /**
     * 记账添加到log表
     *
     * @param accKeepAccount
     */
    private int intsetLog(AccKeepAccount accKeepAccount) {
        String ownerId = "";
        int num = 0;
        List<RefReqList> reqListlist = new ArrayList<>();
        RefReq refReq = new RefReq();
        List<DepReqListInfo> depReqListInfos = new ArrayList<>();
        List<ExpPayReqDetail> expPayReqDetails = new ArrayList<>();
        int no = 0;
        //310退款，311交存，312使用，查询该编号的房屋数量
        switch (accKeepAccount.getBusiType()) {
            case "310":
                reqListlist = refReqListMapper.getInfoByNo(accKeepAccount.getBusiNo());
                refReq = refReqMapper.getInfo(reqListlist.get(0).getReqId());
                no = reqListlist.size();
                break;

            case "311":
                depReqListInfos = depReqListInfoMapper.getInfoByDepReqId(depReqMapper.getInfoByNo(accKeepAccount.getBusiNo()).getId());
                no = depReqListInfos.size();
                break;
            case "312":
                expPayReqDetails = expPayReqDetailMapper.getInfoByPayReqId(expPayReqMapper.getInfoByPayNo(accKeepAccount.getBusiNo()).getId());
                no = expPayReqDetails.size();
                break;
            default:
                num = 0;
                break;
        }

        for (int i = 0; i < no; i++) {
            AccTransactionLog accTransactionLog = new AccTransactionLog();
            BaseHouseInfo baseHouseInfo;
            BigDecimal payAmount = BigDecimal.ZERO;
            BigDecimal payAmountOld = BigDecimal.ZERO;
            List<AccTransactionLog> accTransactionLogNows = new ArrayList<>();
            switch (accKeepAccount.getBusiType()) {
                case "311":
                    baseHouseInfo = baseHouseInfoMapper.getInfo(depReqListInfos.get(i).getHouseId());
                    payAmount = depReqListInfos.get(i).getPayAmount();
                    ownerId = depReqListInfos.get(i).getOwnerNo();
                    accTransactionLog.setIoFlag("In");
                    //状态为可用
                    accTransactionLog.setIsEffective(NumStrEnum.ONE.getNum());
                    //查询金额
                    accTransactionLogNows = accTransactionLogMapper.selectHouseByTallyTimeNow(baseHouseInfo.getId(), accKeepAccount.getTallyTime());
                    //本次添加的金额
                    payAmountOld = moneyAdd(accKeepAccount.getBusiType(), accTransactionLogNows, baseHouseInfo, payAmount, accKeepAccount.getTallyTime());

                    break;
                case "310":
                    //若为全额退款和销户则为失效状态，部分退款为有效
                    baseHouseInfo = baseHouseInfoMapper.getInfo(reqListlist.get(i).getHouseId());
                    //查询金额
                    accTransactionLogNows = accTransactionLogMapper.selectHouseByTallyTimeNow(baseHouseInfo.getId(), accKeepAccount.getTallyTime());
                    payAmount = reqListlist.get(i).getPayAmount();
                    //本次添加的金额
                    payAmountOld = moneyAdd(accKeepAccount.getBusiType(), accTransactionLogNows, baseHouseInfo, payAmount, accKeepAccount.getTallyTime());
                    if (refReq.getRefType().equals("225") || refReq.getRefType().equals("227")) {
                        ownerId = reqListlist.get(i).getOwnerId();
                        int change = accTransactionLogMapper.selectIsEffectiveById(baseHouseInfo.getId(), NumStrEnum.TWO.getNum());
                        if (change != 0) {
                            change = accTransactionLogMapper.updateIsEffectiveById(baseHouseInfo.getId(), NumStrEnum.THREE.getNum(), NumStrEnum.TWO.getNum());
                            if (change == 0) {
                                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                            }
                        }//查询是否有过过户
                        // accTransactionLogMapper.selectNotDusi(reqListlist.get(i).getOwnerId());
                        //若有过户则把状态改为失效
                        accTransactionLogMapper.updateNotDusi(reqListlist.get(i).getHouseId(), "3");
                        accTransactionLog.setIsEffective(NumStrEnum.TWO.getNum());
                        change = accTransactionLogMapper.updateIsEffectiveById(reqListlist.get(i).getHouseId(), NumStrEnum.TWO.getNum(), NumStrEnum.ONE.getNum());
                    } else {
                        ownerId = reqListlist.get(i).getOwnerId();
                        accTransactionLog.setIsEffective(NumStrEnum.ONE.getNum());
                    }
                    accTransactionLog.setIoFlag("Out");
                    break;
                case "312":
                    baseHouseInfo = baseHouseInfoMapper.getInfo(expPayReqDetails.get(i).getHouseId());
                    accTransactionLogNows = accTransactionLogMapper.selectHouseByTallyTimeNow(baseHouseInfo.getId(), accKeepAccount.getTallyTime());
                    payAmount = expPayReqDetails.get(i).getMoney();
                    //本次添加的金额
                    payAmountOld = moneyAdd(accKeepAccount.getBusiType(), accTransactionLogNows, baseHouseInfo, payAmount, accKeepAccount.getTallyTime());
                    ownerId = baseOwnerInfoMapper.selectOwnerId(expPayReqDetails.get(i).getHouseId());
                    accTransactionLog.setIoFlag("Out");
                    accTransactionLog.setIsEffective(NumStrEnum.ONE.getNum());
                    break;
                default:
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
            if (null == baseHouseInfo.getAccrBal()) {
                baseHouseInfo.setAccrBal(BigDecimal.ZERO);
            }
            //Assert.assertNotNull("");
            if (null == baseHouseInfo.getAccountFrozen()) {
                baseHouseInfo.setAccountFrozen(BigDecimal.ZERO);
            }
            accTransactionLog.setAccountFrozen(baseHouseInfo.getAccountFrozen());
            accTransactionLog.setHouseId(baseHouseInfo.getId());
            accTransactionLog.setAccrBal(BigDecimal.ZERO);
            accTransactionLog.setBankId(accKeepAccount.getBankCode());
            accTransactionLog.setTallyDate(accKeepAccount.getTallyTime());
            accTransactionLog.setBusiNo(accKeepAccount.getBusiNo());
            accTransactionLog.setBusiType(accKeepAccount.getBusiType());
            accTransactionLog.setAccountType("325");
            accTransactionLog.setState(NumStrEnum.ONE.getNum());
            accTransactionLog.setOwnerId(ownerId);
            //修改之前的数据
            changeAllMoney(payAmount, accKeepAccount.getTallyTime(), accTransactionLogNows, baseHouseInfo.getId(), NumStrEnum.ZERO.getNum());
            accTransactionLog.setFundBal(payAmountOld);
            accTransactionLog.setPayAmount(payAmount);
            accTransactionLog.setCreater(ShiroUserUtil.getUserName());
            // funBal(accKeepAccount.getTallyTime(), baseHouseInfo.getId(), payAmount, accKeepAccount.getBusiType(), NumStrEnum.ZERO.getNum());
            num = accTransactionLogMapper.insert(accTransactionLog);
            if (num == NumberEnum.ZERO.getNum()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
        }
        return num;

    }

    /**
     * 本次记账的金额
     */
    private BigDecimal moneyAdd(String type, List<AccTransactionLog> accTransactionLogNows, BaseHouseInfo baseHouseInfo, BigDecimal payAmount, String tallyTime) {
        BigDecimal payAmountOld = BigDecimal.ZERO;
        //查询今天之前的金额
        List<AccTransactionLog> accTransactionLogOld = accTransactionLogMapper.selectHouseByTallyTime(baseHouseInfo.getId(), tallyTime);
        if (accTransactionLogOld.size() > 0) {
            for (AccTransactionLog log : accTransactionLogOld) {
                payAmountOld = switchAccAmount(log, payAmountOld, NumStrEnum.ZERO.getNum());
            }
        }
        if (accTransactionLogNows.size() > 0) {
            for (AccTransactionLog nows : accTransactionLogNows) {
                LocalDateTime oldTime = LocalDateTime.parse(nows.getCreateTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                LocalDateTime nowTime = LocalDateTime.parse(DateUtils.getNow(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                if (oldTime.isBefore(nowTime)) {
                    payAmountOld = switchAccAmount(nows, payAmountOld, NumStrEnum.ZERO.getNum());
                }
            }
        }
        if (("311").equals(type)) {
            payAmountOld = payAmountOld.add(payAmount);
        } else {
            payAmountOld = payAmountOld.subtract(payAmount);
        }
        return payAmountOld;
    }

    /**
     * 修改在记账日期之后的金额
     *
     * @param tallyTime
     * @return
     */
    private void changeAllMoney(BigDecimal payAmount, String tallyTime, List<AccTransactionLog> accTransactionLogNows, String id, String type) {
        //查询日期在他之后的log表的数据
        List<AccTransactionLog> accTransactionLogsBefor = accTransactionLogMapper.selectHouseByTallyTimeBefor(id, tallyTime);
        if (accTransactionLogsBefor.size() > 0) {
            for (AccTransactionLog a : accTransactionLogsBefor) {
                //修改金额
                int changeFund = switchAcc(a, payAmount, type);
                if (changeFund == 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                }
            }
        }
        if (accTransactionLogNows.size() > 0) {
            for (AccTransactionLog nows : accTransactionLogNows) {
                LocalDateTime oldTime = LocalDateTime.parse(nows.getCreateTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                LocalDateTime nowTime = LocalDateTime.parse(DateUtils.getNow(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                if (oldTime.isAfter(nowTime)) {
                    int changeFund = switchAcc(nows, payAmount, type);
                    if (changeFund == 0) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                    }
                }
            }
        }
    }

    /**
     * switch
     */
    private int switchAcc(AccTransactionLog nows, BigDecimal payAmountNow, String type) {
        int num = 0;
        switch (nows.getBusiType()) {
            case "311":
                if (type.equals(NumStrEnum.ZERO.getNum())) {
                    payAmountNow = payAmountNow.add(new BigDecimal(nows.getFundBal().toString()));
                } else {
                    payAmountNow = payAmountNow.subtract(new BigDecimal(nows.getFundBal().toString()));
                }

                break;
            case "310":
                if (type.equals(NumStrEnum.ZERO.getNum())) {
                    payAmountNow = payAmountNow.subtract(new BigDecimal(nows.getFundBal().toString()));
                } else {
                    payAmountNow = payAmountNow.add(new BigDecimal(nows.getFundBal().toString()));

                }
                break;
            case "312":
                if (type.equals(NumStrEnum.ZERO.getNum())) {
                    payAmountNow = payAmountNow.subtract(new BigDecimal(nows.getFundBal().toString()));
                } else {
                    payAmountNow = payAmountNow.add(new BigDecimal(nows.getFundBal().toString()));
                }
                break;
        }
        num = accTransactionLogMapper.updateFunBal(nows.getId(), payAmountNow);
        return num;
    }

    /**
     * switch
     *
     * @param nows
     * @param type 0记账，1冲正
     * @return
     */
    private BigDecimal busType(AccTransactionLog nows, BigDecimal payAmount, String type) {
        switch (nows.getBusiType()) {
            case "311":
                if (type.equals(NumStrEnum.ZERO.getNum())) {
                    payAmount = payAmount.add(new BigDecimal(nows.getPayAmount().toString()));
                } else {
                    payAmount = payAmount.subtract(new BigDecimal(nows.getPayAmount().toString()));

                }

                break;
            case "310":
                if (type.equals(NumStrEnum.ZERO.getNum())) {
                    payAmount = payAmount.subtract(new BigDecimal(nows.getPayAmount().toString()));
                } else {
                    payAmount = payAmount.add(new BigDecimal(nows.getPayAmount().toString()));

                }
                break;
            case "312":
                if (type.equals(NumStrEnum.ZERO.getNum())) {
                    payAmount = payAmount.subtract(new BigDecimal(nows.getPayAmount().toString()));
                } else {
                    payAmount = payAmount.add(new BigDecimal(nows.getPayAmount().toString()));
                }
                break;
        }
        return payAmount;
    }

    private BigDecimal switchAccAmount(AccTransactionLog now, BigDecimal payAmount, String type) {
        int num = 0;
        payAmount = busType(now, payAmount, type);
        return payAmount;
    }

    @Override
    public CommonResult delete(String id) {
        return null;
    }

    @Override
    public PageInfo<AccKeepAccount> getList(Page page, AccKeepAccount accKeepAccount) {
        //看登录人的是谁若是银行判断银行，若是管理员看房屋地区
        BaseEntity baseEntity = addSelect();
        if (StringUtils.isNotBlank(baseEntity.getBankId())) {
            accKeepAccount.setBankCode(baseEntity.getBankId());
        }
        if (StringUtils.isNotBlank(baseEntity.getZoneCode())) {
            accKeepAccount.setZoneCode(baseEntity.getZoneCode());
        }
        List<AccKeepAccount> list;
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        BigDecimal pay = BigDecimal.ZERO;
        if (StringUtils.isBlank(accKeepAccount.getFuzzyParam())) {
            list = accKeepAccountMapper.getList(accKeepAccount);
            for (AccKeepAccount a : list) {
                if (a.getBusiType().equals("310") || a.getBusiType().equals("312")) {
                    pay = pay.subtract(a.getPayAmount());
                } else {
                    pay = pay.add(a.getPayAmount());
                }
            }
            AccKeepAccount accKeepAccount1 = new AccKeepAccount();
            accKeepAccount1.setPayAmount(pay);
            BigDecimal sumPayAmountSub = accKeepAccountMapper.getListSumPayAmount(accKeepAccount);
            BigDecimal sumPayAmountAdd = accKeepAccountMapper.getListSumPayAmountAdd(accKeepAccount);
            AccKeepAccount accKeepAccount2 = new AccKeepAccount();
            accKeepAccount2.setPayAmount(sumPayAmountAdd.subtract(sumPayAmountSub));
            list.add(accKeepAccount1);
            list.add(accKeepAccount2);
        } else if (StringUtils.isBlank(accKeepAccount.getBusiNo())) {
            list = accKeepAccountMapper.fuzzyGetList(accKeepAccount.getFuzzyParam(), accKeepAccount.getBankCode(), accKeepAccount.getZoneCode(), accKeepAccount.getAccountState());
            for (AccKeepAccount a : list) {
                if (a.getBusiType().equals("310") || a.getBusiType().equals("312")) {
                    pay = pay.subtract(a.getPayAmount());
                } else {
                    pay = pay.add(a.getPayAmount());
                }
            }
            AccKeepAccount accKeepAccount1 = new AccKeepAccount();
            accKeepAccount1.setPayAmount(pay);
            BigDecimal sumPayAmount = accKeepAccountMapper.fuzzyGetListSumPayAmount(accKeepAccount.getFuzzyParam(), accKeepAccount.getBankCode(), accKeepAccount.getZoneCode(), accKeepAccount.getAccountState());
            BigDecimal sumPayAmountAdd = accKeepAccountMapper.fuzzyGetListSumPayAmountAdd(accKeepAccount.getFuzzyParam(), accKeepAccount.getBankCode(), accKeepAccount.getZoneCode(), accKeepAccount.getAccountState());
            AccKeepAccount accKeepAccount2 = new AccKeepAccount();
            accKeepAccount2.setPayAmount(sumPayAmountAdd.subtract(sumPayAmount));
            list.add(accKeepAccount1);
            list.add(accKeepAccount2);
        } else {
            list = accKeepAccountMapper.fuzzyGetListAndBusiNo(accKeepAccount.getFuzzyParam(), accKeepAccount.getBankCode(), accKeepAccount.getZoneCode(), accKeepAccount.getBillState(), accKeepAccount.getAccountState());
            for (AccKeepAccount a : list) {
                if (a.getBusiType().equals("310") || a.getBusiType().equals("312")) {
                    pay = pay.subtract(a.getPayAmount());
                } else {
                    pay = pay.add(a.getPayAmount());
                }
            }
            AccKeepAccount accKeepAccount1 = new AccKeepAccount();
            accKeepAccount1.setPayAmount(pay);
            BigDecimal sumPayAmount = accKeepAccountMapper.fuzzyGetListAndBusiNoSumPayAmount(accKeepAccount.getFuzzyParam(), accKeepAccount.getBankCode(), accKeepAccount.getZoneCode(), accKeepAccount.getAccountState(), accKeepAccount.getBillState());
            BigDecimal sumPayAmountAdd = accKeepAccountMapper.fuzzyGetListAndBusiNoSumPayAmountAdd(accKeepAccount.getFuzzyParam(), accKeepAccount.getBankCode(), accKeepAccount.getZoneCode(), accKeepAccount.getAccountState(), accKeepAccount.getBillState());

            AccKeepAccount accKeepAccount2 = new AccKeepAccount();
            accKeepAccount2.setPayAmount(sumPayAmountAdd.subtract(sumPayAmount));
            list.add(accKeepAccount1);
            list.add(accKeepAccount2);
        }
        PageInfo<AccKeepAccount> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public AccKeepAccount getInfo(String id) {
        return null;
    }

    @Override
    public PageInfo<AccKeepAccount> getTransInfoList(Page page, AccKeepAccount accKeepAccount) {
        //赋值区域, 暂时不需要
        //accKeepAccount.setLoginZoneCode(zoneCodeUtil.getZoneCode());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<AccKeepAccount> list = accKeepAccountMapper.getTransInfoList(accKeepAccount);
        if (null == list || 0 == list.size()) {
            return new PageInfo<>(list);
        }
        AccKeepAccount total = accKeepAccountMapper.getTransInfoTotal(accKeepAccount);
        setList(list, total);
        PageInfo<AccKeepAccount> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 给list赋值本页合计  总合计
     *
     * @param list
     * @param total
     */
    private void setList(List<AccKeepAccount> list, AccKeepAccount total) {
        if (null == total) {
            total = new AccKeepAccount();
            total.setPayAmount(BigDecimal.ZERO);
        }
        AccKeepAccount pageTotal = new AccKeepAccount();
        BigDecimal payAmount = BigDecimal.ZERO;
        for (AccKeepAccount keepAccount : list) {
            payAmount = payAmount.add(keepAccount.getPayAmount());
        }
        pageTotal.setPayAmount(payAmount);
        list.add(pageTotal);
        list.add(total);
    }

    @Override
    public List<AccKeepAccount> getPayNo() {
        //看登录人的是谁若是银行判断银行，若是管理员看房屋地区
        AccKeepAccount accKeepAccount = new AccKeepAccount();
        BaseEntity baseEntity = addSelect();
        if (StringUtils.isNotBlank(baseEntity.getBankId())) {
            accKeepAccount.setBankCode(baseEntity.getBankId());
        }
        if (StringUtils.isNotBlank(baseEntity.getZoneCode())) {
            accKeepAccount.setZoneCode(baseEntity.getZoneCode());
        }
        List<AccKeepAccount> list = accKeepAccountMapper.getPayNo(accKeepAccount);
        for (AccKeepAccount acc : list) {
            acc.setVerificationTime(DateUtils.getDateNow());
        }
        return list;
    }

    /**
     * 点击验证
     *
     * @param id
     * @param verificationTime
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public AccKeepAccount getInfoById(String id, String verificationTime) {
        String accName = "";
        String accNo = "";
        int num;
        int no = 0;
        LocalDate vaildDate;
        AccKeepAccount accKeepAccount = accKeepAccountMapper.selectAndGetInfo(id);
        //当天验证日期
        LocalDate ver = LocalDate.parse(verificationTime, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //若数据库验证日期为空则不会失效
        if (StringUtils.isBlank(accKeepAccount.getVaildDate())) {
            vaildDate = LocalDate.parse("2999-12-12", DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        } else {
            vaildDate = LocalDate.parse(accKeepAccount.getVaildDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        AccKeepAccount accKeep = new AccKeepAccount();
        //查看该银行结算日期，若没有结算日期则为投产日期
        String time = baseContractorBankInfoMapper.selectSettlementTime(accKeepAccount.getBankCode());
        if (StringUtils.isBlank(time)) {
            BaseContractorBankInfo baseContractorBankInfo = baseContractorBankInfoMapper.getInfoBybankId(accKeepAccount.getBankCode());
            time = baseContractorBankInfo.getCommissioningDate();
            LocalDate bankCodeTime = LocalDate.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            //查看投产日期与现在验证日期相比，投产日期如果在验证日期之后则无法使用
            if (bankCodeTime.isAfter(ver)) {
                accKeep.setVerificationTime(verificationTime);
                accKeep.setMessage("该银行还未开启服务，服务开启日期为" + bankCodeTime);
                return accKeep;
            }
        } else {
            //否则看结算日期，若验证日期在结算日期之前则无法验证
            LocalDate bankCodeTime = LocalDate.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            if (ver.isBefore(bankCodeTime) || bankCodeTime.isEqual(ver)) {
                accKeep.setVerificationTime(verificationTime);
                accKeep.setMessage("该日期本银行已经结算，结算日期为" + bankCodeTime);
                return accKeep;
            }
        }
        if (accKeepAccount.getBusiType().equals("312")) {
            ExpPayReq expPayReq = expPayReqMapper.selectByPayNo(accKeepAccount.getBusiNo());
            if (expPayReq.getStep().equals(NumStrEnum.EIGHT.getNum())) {
                accKeep.setMessage("该业务正在撤销无法记账");
                return accKeep;
            }
        }
        if (ver.isAfter(vaildDate)) {
            accKeep.setVerificationTime(verificationTime);
            accKeep.setMessage("验证日期超过有效期,有效期为" + vaildDate);
            return accKeep;
        }
        switch (accKeepAccount.getBusiType()) {
            case "310":
                no = refReqListMapper.selectCountNum(id);
                List<RefPayInfo> refPayInfo = refPayInfoMapper.selectByNo(accKeepAccount.getBusiNo());
                //查询审核时间验证时间不能超过有效时间
                LocalDate localDateReq = LocalDate.parse(refPayInfo.get(0).getCreateTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                if (localDateReq.isAfter(ver)) {
                    accKeep.setMessage("验证日期小于申请日期(" + localDateReq + ")，请重新选择验证日期");
                    return accKeep;
                }
                accName = refPayInfo.get(0).getBankId();
                accNo = refPayInfo.get(0).getSpAccNo();
                break;
            case "311":
                DepReq depReq = depReqMapper.getInfoByNo(accKeepAccount.getBusiNo());
                //查询审核时间验证时间不能超过有效时间
                LocalDate localDateDep = LocalDate.parse(depReq.getReqDate().substring(0, 10), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                if (localDateDep.isAfter(ver)) {
                    accKeep.setMessage("验证日期小于申请日期(" + localDateDep + ")，请重新选择验证日期");
                    return accKeep;
                }
                no = depReqMapper.selectCountNum(id);
                break;
            case "312":
                ExpPayReq expPayReq = expPayReqMapper.getInfoByPayNo(accKeepAccount.getBusiNo());
                LocalDate localDateExp = LocalDate.parse(expPayReq.getGrantcompletionDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                if (localDateExp.isAfter(ver)) {
                    accKeep.setMessage("验证日期小于申请日期(" + localDateExp + ")，请重新选择验证日期");
                    return accKeep;
                }
                no = expPayReqMapper.selectCountNum(id);
                OrgBankInfo orgBankInfo = orgBankInfoMapper.selectAll(accKeepAccount.getBusiNo());
                BaseBankInfo baseBankInfo = baseBankInfoMapper.getInfo(orgBankInfo.getBankId());
                accName = baseBankInfo.getBankName() + "" + orgBankInfo.getBranchName();
                accNo = orgBankInfo.getAccount();

        }
        if (StringUtils.isBlank(accKeepAccount.getTallyTime())) {
            accKeep.setId(id);
            accKeep.setVerificationState(NumStrEnum.ONE.getNum());
            accKeep.setVerificationTime(verificationTime);
            // accKeep.setTallyTime(verificationTime);
            accKeep.setTallyOper(ShiroUserUtil.getUserName());
            num = accKeepAccountMapper.update(accKeep);
            if (num == 0) {
                accKeep.setMessage("操作失败");
                return accKeep;
            }
        }
        /**
         * 修改状态（退款验证时查看状态是否是最后一次）
         */
        if ((NumStrEnum.ZERO.getNum()).equals(accKeepAccount.getAccountState())) {
            num = selectAccKeepAccount(accKeepAccount.getBusiType(), id, NumStrEnum.ONE.getNum(), NumStrEnum.FIVE.getNum(), NumStrEnum.THREE.getNum(), NumStrEnum.TWO.getNum(), NumStrEnum.ZERO.getNum(), NumStrEnum.THREE.getNum());
            if (num < 1) {
                accKeep.setMessage("该账号已被冻结或撤销无法验证");
                return accKeep;
            }
        }
        AccKeepAccount acc = accKeepAccountMapper.selectAndGetInfo(id);
        // acc.setSpecialAccount(baseContractorBankInfoMapper.getInfoBybankId(acc.getBankCode()).getBankAcc());
        acc.setNum(no);
        acc.setAccBankName(accName);
        acc.setAccBankNo(accNo);
        if (acc.getBusiType().equals("310")) {
            RefReq refReq = refReqMapper.selectReqNo(acc.getBusiNo());
            switch (refReq.getRefType()) {
                case "225":
                    acc.setBusiTypeName("业主销户");
                    break;
                case "226":
                    acc.setBusiTypeName("部分退款");
                    break;
                case "227":
                    acc.setBusiTypeName("全额退款");
                    break;
            }
        }
        if (null == acc.getTallyTime()) {
            acc.setTallyTime(verificationTime);
        }
        return acc;
    }

    @Override
    public AccKeepAccount getListInfo(String id) {
        return accKeepAccountMapper.getListInfo(id);
    }


    /**
     * 查询是谁登录
     *
     * @param
     * @return
     */
    @Override
    public BaseEntity addSelect() {
        String str = ShiroUserUtil.getUserName();
        str = str.substring(0, 1);
        String bankId = "";
        BaseEntity baseEntity = new BaseEntity();
        if ((NumStrEnum.NINE.getNum()).equals(str)) {
            bankId = sysBankOperatorMapper.selectBankId(ShiroUserUtil.getUserName());
            baseEntity.setBankId(bankId);
        } else {
            String zoneCode = operUtil.getZoneCode();
            baseEntity.setZoneCode(zoneCode);
        }
        return baseEntity;
    }

    @Override
    public CommonResult selectState(String bankCode, String tallyTime) {
        int num = NumberEnum.ZERO.getNum();
        List<AccKeepAccount> list = accKeepAccountMapper.selectState(bankCode, tallyTime);
        if (null == list) {
            return CommonResult.ResponseResult(201, "该天有未核对的数据，不能结算");
        } else {
            for (int i = 0; i < list.size(); i++) {
                /**
                 * 修改状态
                 */
                AccKeepAccount accKeepAccount = new AccKeepAccount();
                accKeepAccount.setId(list.get(i).getId());
                accKeepAccount.setUpdateTime(DateUtils.getDateNow());
                accKeepAccount.setSettlementTime(DateUtils.getDateNow());
                accKeepAccount.setSettlementOper(ShiroUserUtil.getUserName());
                num = accKeepAccountMapper.update(accKeepAccount);
                if (num == NumberEnum.ZERO.getNum()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                }
            }
        }
        return CommonResult.ResponseResult(num);
    }

    /**
     * 通过记账id查询出相对应的数据库的相对应的数据
     *
     * @param type 记账表的业务类型
     * @param id   记账id
     * @return
     */
    public int selectAccKeepAccount(String type, String id, String state, String accNoState, String rstep, String dstep, String typeNum, String lstate) {
        int no = NumberEnum.ZERO.getNum();
        String date = null;
        List<String> list;
        if ((NumStrEnum.ONE.getNum()).equals(typeNum)) {
            date = DateUtils.getDateNow();
        }
        switch (type) {
            case "310":
                List<RefPayInfo> refPay = refPayInfoMapper.selectReq(id);
                if (rstep.equals(NumStrEnum.FOUR.getNum())) {
                    List<RefPayInfo> refPayInfos = refPayInfoMapper.selectAllPayNo(refPay.get(0).getReqId(), "1,5");
                    if (null != refPayInfos) {
                        if (refPayInfos.size() == 1) {
                            no = refReqMapper.updateStep(refPayInfos.get(0).getReqId(), NumStrEnum.FOUR.getNum());
                            if (no == NumberEnum.ZERO.getNum()) {
                                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                            }
                        }
                    }
                } else {
                    List<RefPayInfo> refPayInfos = refPayInfoMapper.selectAllPayNo(refPay.get(0).getReqId(), NumStrEnum.ONE.getNum());
                    if (null != refPayInfos) {
                        if (refPayInfos.size() == 1) {
                            no = refReqMapper.updateStep(refPayInfos.get(0).getReqId(), NumStrEnum.THREE.getNum());
                            if (no == NumberEnum.ZERO.getNum()) {
                                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                            }
                        }
                    }
                }
                list = refPayInfoMapper.selectPayInfoById(id);
                for (int i = 0; i < list.size(); i++) {
                    no = refPayInfoMapper.updateState(list.get(i), state, accNoState, date);
                    if (no == NumberEnum.ZERO.getNum()) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                    }

                }
                break;
            case "311":
                list = depReqMapper.selectPayInfoById(id);
                for (int i = 0; i < list.size(); i++) {
                    no = depReqMapper.updateStep(list.get(i), dstep, date);
                    if (no == NumberEnum.ZERO.getNum()) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                    }
                    List<DepReqListInfo> listInfos = depReqListInfoMapper.getInfoByDepReqId(depReqMapper.getInfoByNo(accKeepAccountMapper.getListInfo(id).getBusiNo()).getId());
                    for (DepReqListInfo l : listInfos) {
                        if (lstate.equals("3")) {
                            no = depReqListInfoMapper.updateState(l.getId(), lstate);
                            if (no == NumberEnum.ZERO.getNum()) {
                                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                            }
                        }

                    }
                }
                break;
            case "312":
                list = expPayReqMapper.selectPayInfoById(id);
                for (int i = 0; i < list.size(); i++) {
                    no = expPayReqMapper.updateStep(list.get(i), dstep, date);
                    if (no == NumberEnum.ZERO.getNum()) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                    }
                }
        }
        return no;
    }

    /**
     * 冲正
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult reverse(String id) {
        AccKeepAccount accKeep = accKeepAccountMapper.getInfo(id);
        if (null == accKeep) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "操作失败未查询到数据");

        }
        if (accKeep.getAccountState().equals("2") || accKeep.getAccountState().equals("3")) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该数据已结算或核对，不能冲正");
        }
        List<AccTransactionLog> accTransactionLog = accTransactionLogMapper.selectByBusNo(accKeep.getBusiNo());
        for (AccTransactionLog a : accTransactionLog) {
            int time = accTransactionLogMapper.selectEndByHid(a.getHouseId(), accKeep.getTallyTime());
            if (time > 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "不是最后记账数据，不能冲正");
            }
            //查看有没有同一时间的记账数据，若有的话则判断添加时间
            List<AccTransactionLog> nowList = accTransactionLogMapper.selectEndByHidAll(a.getHouseId(), accKeep.getTallyTime());
            if (0 != nowList.size()) {
                int no = accTransactionLogMapper.selectHouseByCreateNow(a.getHouseId(), a.getCreateTime());
                if (no > 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "不是最后记账数据，不能冲正!");
                }
            }
        }
        int num;
        AccKeepAccount accKeepAccount = accKeepAccountMapper.getListInfo(id);
        //只能冲正最后一次的使用
        if (("312").equals(accKeepAccount.getBusiType())) {
            ExpPayReq expPayReq = expPayReqMapper.getInfoByPayNo(accKeepAccount.getBusiNo());
            ExpProjectReq expProjectReq = expProjectReqMapper.getInfoById(expPayReq.getReqId());
            if (expProjectReq.getPayCount() != expPayReq.getReqNum()) {
                int max = expPayReqMapper.maxNum(expPayReq.getReqId());
                if (max != expPayReq.getReqNum()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "不是最后一笔拨款记账数据或上一笔拨款数据在业务处理中，不能冲正");
                }
            }
        }
        //查询出该记账的log表的数据
        List<AccTransactionLog> list = accTransactionLogMapper.selectByBusNo(accKeepAccount.getBusiNo());
        for (AccTransactionLog trans : list) {
            if (("311").equals(accKeepAccount.getBusiType())) {
                num = depReqListInfoMapper.selectCountHouse(trans.getHouseId());
                if (num > 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该业务下的房间有在途交存，无法冲正");
                }
                BaseHouseInfo ba = baseHouseInfoMapper.getInfo(trans.getHouseId());
                if (ba.getFlowInProgress() != null && ba.getAccountFrozen().compareTo(BigDecimal.ZERO) != 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该业务下的房间有退款或已经使用，无法冲正");
                }
            } else if (("310").equals(accKeepAccount.getBusiType())) {
                if (baseHouseInfoMapper.getInfo(trans.getHouseId()).getAccountFrozen().equals("ref_req")) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该业务下的房间有退款业务，无法冲正");
                }
                List<RefReqList> ref = refReqListMapper.getInfoByNo(accKeepAccount.getBusiNo());
                if (ref.get(0).getRefType().equals("225")) {
                    for (RefReqList r : ref) {
                        BaseHouseInfo base = baseHouseInfoMapper.getInfo(r.getHouseId());
                        int no = baseHouseInfoMapper.selectByBuildAndFloor(base.getBuildNo(), base.getCellNo(), base.getFloorNo(), base.getRoomNo());
                        if (no > 0) {
                            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该房间已经新建无法冲正");
                        }
                    }

                } else if (ref.get(0).getRefType().equals("227")) {
                    for (RefReqList r : ref) {
                        BaseOwnerInfo baseOwnerInfo = baseOwnerInfoMapper.getInfoByAccNo(r.getHouseId());
                        if (null != baseOwnerInfo) {
                            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该业务下的房间已经维护业主无法冲正");
                        }
                    }
                }
            }
        }
        int no = accKeepAccountMapper.updateAccState(id, NumStrEnum.ZERO.getNum(), null);
        if (no == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        num = InsertAccReverseRecord(accKeepAccount);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        switch (accKeepAccount.getBusiType()) {
            //退款
            case "310":
                num = changereq(accKeepAccount, NumStrEnum.ZERO.getNum(), NumStrEnum.ZERO.getNum());
                if (num == NumberEnum.ZERO.getNum()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                }
                break;
            //交存
            case "311":
                num = reverseDeposit(accKeepAccount);
                if (num == NumberEnum.ZERO.getNum()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                }
                break;
            //使用
            case "312":
                num = reverseUse(accKeepAccount);
                if (num == NumberEnum.ZERO.getNum()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                }
                break;
        }
        //修改log表的金额
        for (AccTransactionLog trans : list) {
            //修改log的状态
            num = accTransactionLogMapper.updateStateById(NumStrEnum.ZERO.getNum(), trans.getId());
            if (num == NumberEnum.ZERO.getNum()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
        }
        //修改承办银行的金额
        if (accKeepAccount.getBusiType().equals("311")) {
            accKeepAccount.setPayAmount(accKeepAccount.getPayAmount().negate());
        }
        num = accKeepAccountMapper.updateBankMoney(accKeepAccount.getBankCode(), accKeepAccount.getPayAmount());
        return CommonResult.ResponseResult(num);
    }

    /**
     * 冲正 插入AccReverseRecord
     *
     * @param accKeepAccount
     */
    private int InsertAccReverseRecord(AccKeepAccount accKeepAccount) {
        int num;
        AccReverseRecord accReverseRecord = new AccReverseRecord();
        accReverseRecord.setId(UUIDUtil.getUUID());
        accReverseRecord.setBusiNo(accKeepAccount.getBusiNo());
        accReverseRecord.setBusiType(accKeepAccount.getBusiType());
        //accReverseRecord.getAccountPeriod(accKeepAccount.getBusiNo());账期
        accReverseRecord.setCreateTime(DateUtils.getDateNow());
        accReverseRecord.setCreater(ShiroUserUtil.getUserName());
        accReverseRecord.setBankCode(accKeepAccount.getBankCode());
        accReverseRecord.setTallyDate(accKeepAccount.getTallyTime());
        accReverseRecord.setTallyOper(accKeepAccount.getTallyOper());
        accReverseRecord.setSpecialAccount(accKeepAccount.getSpecialAccount());
        accReverseRecord.setPayAmount(accKeepAccount.getPayAmount());
        accReverseRecord.setReqName(accKeepAccount.getReqName());
        accReverseRecord.setPayMethod(accKeepAccount.getPayMethod());
        accReverseRecord.setReverseOper(ShiroUserUtil.getUserName());
        accReverseRecord.setRemark(accKeepAccount.getRemark());
        accReverseRecord.setRegionNo(accKeepAccount.getRegionId());
        num = accReverseRecordMapper.insert(accReverseRecord);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        return num;
    }

    /**
     * 冲正 交存 311
     *
     * @param accKeepAccount
     * @return
     */
    private int reverseDeposit(AccKeepAccount accKeepAccount) {
        int num;
        DepReq depReq = new DepReq();
        depReq.setNo(accKeepAccount.getBusiNo());
        depReq.setStep(NumStrEnum.TWO.getNum());
        depReq.setState(NumStrEnum.ONE.getNum());
        num = depReqMapper.updateByNo(depReq);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        changedep(accKeepAccount, NumStrEnum.ONE.getNum());
        return num;
    }

    /**
     * 冲正记账里的交存,accFrozeType冻结金额若为0则加，为1则减2为不动，funType账户余额0加1减
     * *
     */
    private int changedep(AccKeepAccount accKeepAccount, String funType) {
        int num = NumberEnum.ZERO.getNum();
        DepReq depReq = depReqMapper.getInfoByNo(accKeepAccount.getBusiNo());
        if ((NumStrEnum.ONE.getNum()).equals(funType)) {
            depReqMapper.updateHfmpdate(accKeepAccount.getBusiNo(), null);
        }
        List<DepReqListInfo> list = depReqListInfoMapper.getInfoByDepReqId(depReq.getId());
        for (DepReqListInfo item : list) {
            if ((NumStrEnum.ONE.getNum()).equals(funType)) {
                num = depReqListInfoMapper.updateState(item.getId(), NumStrEnum.THREE.getNum());
            } else {
                num = depReqListInfoMapper.updateState(item.getId(), NumStrEnum.FOUR.getNum());
            }
            if (num == NumberEnum.ZERO.getNum()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
            BaseHouseInfo house = baseHouseInfoMapper.getInfo(item.getHouseId());
            if ((NumStrEnum.ONE.getNum()).equals(funType)) {
                house.setFlowInProgress("deposit");
            } else {
                house.setFlowInProgress(NumStrEnum.ZERO.getNum());
            }
            num = baseHouseInfoMapper.update(house);
            if (num == NumberEnum.ZERO.getNum()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
            num = dueState(item.getHouseId(), item.getPayAmount(), funType);
        }
        return num;
    }

    /**
     * 交存状态
     */
    public int dueState(String houseId, BigDecimal payAmount, String funType) {
        BigDecimal dep = accTransactionLogMapper.selectMoneyDepAll(houseId);
        BigDecimal ref = accTransactionLogMapper.selectMoneyReqAll(houseId);
        BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(houseId);
        if ((NumStrEnum.ZERO.getNum()).equals(funType)) {
            //若为记账则看该房屋之前的记账和退款加上这次的是否大于初交，若大于则为多交2，小于小交3，等于未交4，足额1
            dep = dep.subtract(ref).add(payAmount);
            baseHouseInfo.setFundBal(baseHouseInfo.getFundBal().add(payAmount));
            baseHouseInfo.setFlowInProgress(NumStrEnum.ZERO.getNum());
        } else {
            //若为冲正则看该房屋之前的记账和退款加上这次的是否大于初交，若大于则为多交3，小于小交2，等于未交4，足额1
            dep = dep.subtract(ref).subtract(payAmount);
            baseHouseInfo.setFundBal(baseHouseInfo.getFundBal().subtract(payAmount));
            baseHouseInfo.setFlowInProgress("deposit");
        }
        baseHouseInfo.setDueState(dueStateType(baseHouseInfo, dep));
        return baseHouseInfoMapper.updateToAccKeep(baseHouseInfo.getFundBal(), baseHouseInfo.getId(), baseHouseInfo.getDueState(), baseHouseInfo.getFlowInProgress());
    }

    /**
     * 根据状态修改数据
     * 冲正记账,accFrozeType冻结金额若为0则加，为1则减2为不动，funType账户余额0加1减
     */
    private int listUpdate(RefReqList item, BigDecimal payAmount, int num, String accFrozeType, String funType) {
        BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(item.getHouseId());
        //总共缴存的金额
        BigDecimal dep = accTransactionLogMapper.selectMoneyDepAll(baseHouseInfo.getId());
        //总共退款的金额
        BigDecimal ref = accTransactionLogMapper.selectMoneyReqAll(baseHouseInfo.getId());
        if (null == item.getPayAccrAmount()) {
            item.setPayAccrAmount(BigDecimal.ZERO);
        }
        if (null == ref) {
            ref = BigDecimal.ZERO;
        }
        if (null == baseHouseInfo.getAccrBal()) {
            baseHouseInfo.setAccrBal(BigDecimal.ZERO);
        }
        if (null == item.getPayAccrCal()) {
            item.setPayAccrCal(BigDecimal.ZERO);
        }
        if (null == item.getPayFundAmount()) {
            item.setPayFundAmount(BigDecimal.ZERO);
        }//冲正
        if (NumStrEnum.ZERO.getNum().equals(accFrozeType)) {
            dep = dep.subtract(ref).add(item.getPayFundAmount());
            baseHouseInfo.setAccountFrozen(payAmount);
        } else if (NumStrEnum.ONE.getNum().equals(accFrozeType)) {
            dep = dep.subtract(ref).subtract(item.getPayFundAmount());
            baseHouseInfo.setAccountFrozen(payAmount.negate());
        }
        if (NumStrEnum.ZERO.getNum().equals(funType)) {
            baseHouseInfo.setFundBal(item.getPayFundAmount());
            if (null != item.getPayAccrAmount() && item.getPayAccrAmount().compareTo(BigDecimal.ZERO) != 0) {
                baseHouseInfo.setAccrBal(baseHouseInfo.getAccrBal().add(item.getPayAccrAmount()));
            }
        } else if (NumStrEnum.ONE.getNum().equals(funType)) {
            if (null != item.getPayAccrAmount() && item.getPayAccrAmount().compareTo(BigDecimal.ZERO) != 0) {
                baseHouseInfo.setAccrBal(baseHouseInfo.getAccrBal().subtract(item.getPayAccrAmount()));
            }
            baseHouseInfo.setFundBal(item.getPayFundAmount().negate());
        }
        baseHouseInfo.setDueState(dueStateType(baseHouseInfo, dep));
        num = baseHouseInfoMapper.updateMoneyById(baseHouseInfo);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }

        return num;
    }


    public String dueStateType(BaseHouseInfo baseHouseInfo, BigDecimal dep) {
        //部分退款修改交存状态
        BigDecimal paramValue;
        String dueState;
        //参数设置：当实交金额与应交金额差额在几元之内时，认定已足额交存
        String param = sysCoreParamMapper.getParamValueByCode("13");
        if (StringUtils.isNotBlank(param)) {
            paramValue = new BigDecimal(param);
        } else {
            paramValue = BigDecimal.ZERO;
        }
        if (dep.compareTo(BigDecimal.ZERO) == 0) {
            dueState = NumStrEnum.FOUR.getNum();
        } else if (dep.compareTo(baseHouseInfo.getFirstDue().subtract(paramValue)) >= 0 && dep.compareTo(baseHouseInfo.getFirstDue()) <= 0) {
            dueState = NumStrEnum.ONE.getNum();
        } else if (dep.compareTo(baseHouseInfo.getFirstDue().subtract(paramValue)) < 0) {
            dueState = NumStrEnum.THREE.getNum();
        } else {
            dueState = NumStrEnum.TWO.getNum();
        }
        return dueState;
    }

    /**
     * 冲正 使用 312
     *
     * @param accKeepAccount
     * @return
     */
    private int reverseUse(AccKeepAccount accKeepAccount) {
        int num;
        ExpPayReq expPayReq = new ExpPayReq();
        expPayReq.setPayNo(accKeepAccount.getBusiNo());
        expPayReq.setStep(NumStrEnum.FOUR.getNum());
        num = expPayReqMapper.updateStepByPayNo(expPayReq);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        num = reverseUseSub(accKeepAccount, NumStrEnum.ZERO.getNum());
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        return num;
    }

    /**
     * 修改使用
     */
    private int ChangeExp(ExpPayReq expPayReq, ExpProjectReq expProjectReq, String acc) {
        int num;
        List<ExpPayReqDetail> exp = expPayReqDetailMapper.getInfoByPayReqId(expPayReq.getId());
        //修改状态查看是否是决算付款若不是则直接修改exp_projectreq 为6，否则查看是不是最后一次若是并且有质保金则改为8否则改为7
        if (acc.equals(NumStrEnum.TWO.getNum())) {
            if (expProjectReq.getIsLast() == 1) {
                if ((expProjectReq.getPayCount() - 1) == (expPayReq.getReqNum())) {
                    expProjectReq.setStep(NumStrEnum.SEVEN.getNum());
                } else if ((expProjectReq.getPayCount()) == (expPayReq.getReqNum())) {
                    expProjectReq.setStep(NumStrEnum.EIGHT.getNum());
                } else {
                    expProjectReq.setStep(NumStrEnum.SIX.getNum());
                }
            } else {
                expProjectReq.setStep(NumStrEnum.SIX.getNum());
                if ((expProjectReq.getPayCount()) == (expPayReq.getReqNum())) {
                    expProjectReq.setStep(NumStrEnum.EIGHT.getNum());
                }
            }
        } else {
            //退回前一个的状态
            ExpPayReq expPayReq1 = expPayReqMapper.numAndReqId((expPayReq.getReqNum()) - 1, expPayReq.getReqId());
            //如果是空则为4，否则看是否有质保金若没有质保金则为6有最后一次为7
            if (expPayReq1 == null) {
                expProjectReq.setStep(NumStrEnum.FOUR.getNum());
            } else if (expProjectReq.getIsLast() == 1) {
                if ((expProjectReq.getPayCount()) == (expPayReq.getReqNum())) {
                    expProjectReq.setStep(NumStrEnum.SEVEN.getNum());
                } else {
                    expProjectReq.setStep(NumStrEnum.SIX.getNum());
                }
            } else {
                expProjectReq.setStep(NumStrEnum.SIX.getNum());
            }
        }
        num = expProjectReqMapper.changeStep(expProjectReq.getId(), expProjectReq.getStep());
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        return num;
    }
    /**
     * 冲正使用子方法，小蕊用
     * cdg
     * 20190806
     * @param accKeepAccount
     * @return
     */
    /**
     * 从关联expPayReq中payno，exp中id与detial中payid关联 查出mony和houseid
     * 通过houseid修改house
     * 把house中funbal=fund_bal+money，并house表中account_frozen=account_frozen+money
     */
    private int reverseUseSub(AccKeepAccount accKeepAccount, String accFroze) {
        int num = 0;
        //金额
        ExpPayReq expPayReq = expPayReqMapper.getInfoByPayNo(accKeepAccount.getBusiNo());
        String step = expPayReqMapper.getStep(expPayReq.getReqId(), expPayReq.getReqNum() - 1);
        if (expPayReq.getReqNum() != 1 && !NumStrEnum.FIVE.getNum().equals(step)) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "上一笔拨款未记账，请处理");
        }
        ExpProjectReq expProjectReq = expProjectReqMapper.getInfoById(expPayReq.getReqId());
        //校验当前记账数据之前的数据是否已经记账
        List<ExpPayReqDetail> exp = expPayReqDetailMapper.getInfoByPayReqId(expPayReq.getId());
        for (ExpPayReqDetail expPayReqDetail : exp) {
            BigDecimal money = BigDecimal.ZERO;
            BaseHouseInfo baseHouseInfo = new BaseHouseInfo();
            baseHouseInfo.setId(expPayReqDetail.getHouseId());
            //若有质保金记账则在决算时房屋已经把质保金的金额删除，但银行不删除
            if (expProjectReq.getIsLast() == 1) {
                if ((expProjectReq.getPayCount() - 1) == (expPayReq.getReqNum())) {
                    ExpPayReq expPayReq1 = expPayReqMapper.numAndReqId((expPayReq.getReqNum()) + 1, expPayReq.getReqId());
                    ExpPayReqDetail expPayReqDetail1 = expPayReqDetailMapper.getInfoByPayReqIdAndHouseId(expPayReq1.getId(), expPayReqDetail.getHouseId());
                    money = money.add(expPayReqDetail1.getMoney());
                    //若有质保金记账则在质保金记账时，房屋金额不变，只修改银行
                } else if ((expProjectReq.getPayCount()) == (expPayReq.getReqNum())) {
                    num = ChangeExp(expPayReq, expProjectReq, accFroze);
                    return num;
                }
            }
            if (accFroze.equals(NumStrEnum.TWO.getNum())) {
                baseHouseInfo.setFundBal(expPayReqDetail.getMoney().add(money).negate());
                baseHouseInfo.setAccountFrozen(expPayReqDetail.getMoney().add(money).negate());
            } else {
                expPayReq.setHfmpDate(null);
                num = expPayReqMapper.updateHfmpDate(expPayReq.getHfmpDate(), expPayReq.getId());
                if (num == NumberEnum.ZERO.getNum()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                }
                baseHouseInfo.setFundBal(expPayReqDetail.getMoney().add(money));
                baseHouseInfo.setAccountFrozen(expPayReqDetail.getMoney().add(money));
            }
            num = baseHouseInfoMapper.updateMoneyById(baseHouseInfo);
            if (num == NumberEnum.ZERO.getNum()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }

        }
        num = ChangeExp(expPayReq, expProjectReq, accFroze);

        return num;
    }

    /**
     * 查询这个银行的结息日期
     *
     * @param bankCode
     * @return
     */
    @Override
    public String tallyTime(String bankCode) {
        String time = baseContractorBankInfoMapper.selectSettlementTime(bankCode);
        if (StringUtils.isBlank(time)) {
            BaseContractorBankInfo baseContractorBankInfo = baseContractorBankInfoMapper.getInfoBybankId(bankCode);
            time = baseContractorBankInfo.getCommissioningDate();
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date;
            try {
                date = sdf.parse(time);
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                cal.add(Calendar.DATE, 1);
                date = cal.getTime();
                time = sdf.format(date);
            } catch (ParseException e) {
                log.error("ParseException错误信息:()", e.getMessage(), e);
            }
        }
        return time;
    }

    @Override
    public PageInfo<SettleAccounts> getCountList(Page page, SettleAccounts settleAccounts) {
        //查询银行的结算日期
        String time = baseContractorBankInfoMapper.selectSettlementTime(settleAccounts.getBankCode());
        //如果结算日期为空则为开始使用日期
        if (StringUtils.isBlank(time)) {
            time = baseContractorBankInfoMapper.getInfoBybankId(settleAccounts.getBankCode()).getCommissioningDate();
        }
        LocalDate getHfmpDate = LocalDate.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate startDate = LocalDate.parse(settleAccounts.getTallyTimeStart(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        if (startDate != null) {
            if (getHfmpDate.isEqual(startDate)) {
                settleAccounts.setTallyTimeStart(getHfmpDate.toString());
            }
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<SettleAccounts> list = accKeepAccountMapper.getCountList(settleAccounts.getBankCode(), settleAccounts.getTallyTimeStart(), settleAccounts.getTallyTimeEnd());
        int num = 0;
        BigDecimal amount = BigDecimal.ZERO;
        BigDecimal payOutAmount = BigDecimal.ZERO;
        int payOutAmountNum = 0;
        int amountNum = 0;
        for (SettleAccounts a : list) {
            payOutAmount = payOutAmount.add(a.getPayOutAmount());
            amount = amount.add(a.getAmount());
            num = num + a.getNum();
            payOutAmountNum = payOutAmountNum + Integer.parseInt(a.getPayOutAmountNum());
            amountNum = amountNum + Integer.parseInt(a.getAmountNum());
        }
        SettleAccounts settleAccounts1 = new SettleAccounts();
        settleAccounts1.setAmount(amount);
        settleAccounts1.setNum(num);
        settleAccounts1.setAmountNum(amountNum + "");
        settleAccounts1.setPayOutAmount(payOutAmount);
        settleAccounts1.setPayOutAmountNum(payOutAmountNum + "");
        SettleAccounts settleAccounts2 = accKeepAccountMapper.getCountListSum(settleAccounts.getBankCode(), settleAccounts.getTallyTimeStart(), settleAccounts.getTallyTimeEnd());
        list.add(settleAccounts1);
        list.add(settleAccounts2);
        PageInfo<SettleAccounts> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 日终核对-核对-列表
     *
     * @param page
     * @param accKeepAccount
     * @return
     */
    @Override
    public PageInfo<AccKeepAccount> getListByBankCodeAndTallyTime(Page page, AccKeepAccount accKeepAccount, String fuzzy) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        accKeepAccount.setAccountState("1,2,3");
        accKeepAccount.setState(NumStrEnum.ONE.getNum());
        List<AccKeepAccount> list = new ArrayList<AccKeepAccount>();
        if (StringUtils.isBlank(fuzzy)) {
            list = accKeepAccountMapper.getListByBankCodeAndTallyTime(accKeepAccount);
            BigDecimal payAmoutSum = BigDecimal.ZERO;
            for (AccKeepAccount a : list) {
                payAmoutSum = payAmoutSum.add(a.getPayAmount());
            }
            AccKeepAccount accKeepAccount1 = new AccKeepAccount();
            AccKeepAccount accKeepAccount2 = new AccKeepAccount();
            BigDecimal payAmount = accKeepAccountMapper.getListByBankCodeAndTallyTimeSum(accKeepAccount);
            list.add(accKeepAccount2);
            accKeepAccount2.setPayAmount(payAmoutSum);
            accKeepAccount1.setPayAmount(payAmount);
            list.add(accKeepAccount1);
        } else {
            AccKeepAccount accKeepAccount1 = new AccKeepAccount();
            AccKeepAccount accKeepAccount2 = new AccKeepAccount();
            accKeepAccount.setFuzzy(fuzzy);
            list = accKeepAccountMapper.getListByBankCodeAndTallyTimeFuzzy(accKeepAccount);
            BigDecimal payAmoutSum = BigDecimal.ZERO;
            for (AccKeepAccount a : list) {
                payAmoutSum = payAmoutSum.add(a.getPayAmount());
            }
            BigDecimal payAmount = accKeepAccountMapper.getListByBankCodeAndTallyTimeFuzzySum(accKeepAccount);
            list.add(accKeepAccount2);
            accKeepAccount2.setPayAmount(payAmoutSum);
            accKeepAccount1.setPayAmount(payAmount);
            list.add(accKeepAccount1);
        }
        PageInfo<AccKeepAccount> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


    /**
     * 核对时进入财务接口
     */
    public String addFin(String ids) {
        String[] idArr = ids.split(",");
        List<AccKeepAccount> deps = new ArrayList<>();
        List<AccKeepAccount> reqs = new ArrayList<>();
        List<AccKeepAccount> exps = new ArrayList<>();
        for (String id : idArr) {
            //310退款  311交存312支用
            AccKeepAccount accKeepAccount = accKeepAccountMapper.getInfo(id);
            switch (accKeepAccount.getBusiType()) {
                case "310":
                    reqs.add(accKeepAccount);
                    break;
                case "311":
                    deps.add(accKeepAccount);
                    break;
                case "312":
                    exps.add(accKeepAccount);
                    break;
                default:
                    break;
            }
        }
        if (deps.size() != 0) {
            addaccVouch(deps);
        }
        if (reqs.size() != 0) {
            addaccVouch(reqs);
        }
        if (exps.size() != 0) {
            addaccVouch(exps);
        }
        return NumStrEnum.ONE.getNum();
    }

    private String ccodeBank(String bankId) {
        String sys = sysCoreParamMapper.getParamValueByCode("59");
        String ccodeBank = "";
        if (null != sys && sys.equals(NumStrEnum.ONE.getNum())) {
            ccodeBank = baseContractorBankInfoMapper.getInfoBybankId(bankId).getFinanceNo();
            if (StringUtils.isBlank(ccodeBank)) {
                String firstLevelCode = sysCoreParamMapper.getParamValueByCode("62");
                BaseBankInfo baseBankInfo = baseBankInfoMapper.getInfo(bankId);
                ccodeBank = baseBuildInfoServiceImpl.addInster(firstLevelCode, baseBankInfo.getBankName());
                int no = baseBankInfoMapper.updateFinanceNo(bankId, ccodeBank);
                if (no == 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "银行的财务编号添加失败，请联系管理员");
                }
            }
        }
        return ccodeBank;
    }

    /**
     * 添加到link表
     */
    private int addLink(String num, AccKeepAccount accKeepAccount, Integer isignseq, String ccode, BigDecimal amount) {
        Map<String, Object> map = new HashMap<>();
        AccBusiVouchLink accBusiVouchLink = new AccBusiVouchLink();
        accBusiVouchLink.setInoId(num);
        accBusiVouchLink.setCcode(ccode);

        accBusiVouchLink.setIsignseq(isignseq);
        if (3 == isignseq) {
            accBusiVouchLink.setPayAmount(amount);
        } else {
            accBusiVouchLink.setPayAmount(accKeepAccount.getPayAmount());
        }
        accBusiVouchLink.setBusiNo(accKeepAccount.getBusiNo());
        accBusiVouchLink.setAccountPeriod(DateUtils.getYyyyMm());
        int no = accBusiVouchLinkMapper.insert(accBusiVouchLink);
        if (no == 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "添加到数据库失败");
        }
        return no;
    }

    /**
     * 非汇总的交存和退款的添加到财务
     *
     * @param accKeepAccount
     * @return
     */
    private String addFinanceDepReq(List<AccKeepAccount> accKeepAccount, BigDecimal payAmounts) {
        //查询财务编号
        List<Map<String, Object>> list;
        //查询bankcode
        String ccodeBank = ccodeBank(accKeepAccount.get(0).getBankCode());
        list = addList(ccodeBank, payAmounts, accKeepAccount, accKeepAccount.get(0).getBusiType());
        String num = connect(list, "http://192.168.31.101:8091/AccVouch/writeAccVouch");
        if (num == null) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "传给财务数据库时数据出现问题");
        }
        for (AccKeepAccount a : accKeepAccount) {
            if (a.getPayAmount().compareTo(BigDecimal.ZERO) != 0) {
                int no = accBusiVouchLinkMapper.updateInoid(num, a.getBusiNo());
                if (no <= 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "修改财务数据有问题");
                }
            }
        }
        return NumStrEnum.ONE.getNum();
    }

    /**
     * 使用map
     *
     * @param map
     * @return
     */
    private Map<String, Object> mapExp(Map<String, Object> map) {
        Map<String, Object> maps = new HashMap<>();
        maps.put("baseName", sqlName());
        maps.put("iperiod", DateUtils.getMmNow());
        maps.put("csign", "用");
        maps.put("isignseq", NumStrEnum.THREE.getNum());
        maps.put("inid", map.get("num"));
        maps.put("billDate", DateUtils.getNow());
        maps.put("cdigest", "维修资金使用");
        maps.put("ccode", map.get("ccode"));
        maps.put("amount", map.get("amount"));
        return maps;
    }

    /**
     * 交存map
     *
     * @param map
     * @return
     */
    private Map<String, Object> mapDep(Map<String, Object> map) {
        Map<String, Object> maps = new HashMap<>();
        maps.put("baseName", sqlName());
        maps.put("iperiod", DateUtils.getMmNow());
        maps.put("csign", "缴");
        maps.put("isignseq", NumStrEnum.TWO.getNum());
        maps.put("inid", map.get("num"));
        maps.put("billDate", DateUtils.getNow());
        maps.put("cdigest", "维修资金交存");
        maps.put("ccode", map.get("ccode"));
        maps.put("amount", map.get("amount"));
        return maps;
    }

    /**
     * 退款
     *
     * @param map
     * @return
     */
    //  *baseName: string 数据库名称(系统参数设置项 ufdata_xxx_)
//    *iperiod：int    会计月度
//    *csign：string    凭证字（缴、用、取、息）
//    *isignseq：int    凭证类别（2、3、4、7）
//    *inid：int    凭证顺序号
//    *billDate : string    记账日期
//    *cdigest：string 摘要
//    *ccode：string 科目代码
//    *amount：float 发生金额
    public Map<String, Object> map(Map<String, Object> map) {
        Map<String, Object> maps = new HashMap<>();
        maps.put("baseName", sqlName());
        maps.put("iperiod", DateUtils.getMmNow());
        maps.put("csign", "取");
        maps.put("isignseq", NumStrEnum.FOUR.getNum());
        maps.put("inid", map.get("num"));
        maps.put("billDate", DateUtils.getNow());
        maps.put("cdigest", "维修资金支取");
        maps.put("ccode", map.get("ccode"));
        maps.put("amount", map.get("amount"));
        return maps;
    }

    /**
     * 添加财务的形式
     *
     * @param ccode           财务代码
     * @param amount          总金额
     * @param accKeepAccounts 财务
     * @param type            状态310,311
     * @return
     */
    public List<Map<String, Object>> addList(String ccode, BigDecimal amount, List<AccKeepAccount> accKeepAccounts, String type) {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> maps = new HashMap<>();
        maps.put("num", 1);
        maps.put("ccode", ccode);
        maps.put("amount", amount);
        Map<String, Object> firstMap;
        Map<String, Object> nextMap;
        if (("310").equals(type)) {
            firstMap = map(maps);
        } else {
            firstMap = mapDep(maps);
        }
        list.add(0, firstMap);
        List<String> tempList = new ArrayList<>();
        for (AccKeepAccount i : accKeepAccounts) {
            if (!tempList.contains(i.getFinanceCode())) {
                tempList.add(i.getFinanceCode());
            }
        }
        for (int i = 0; i < accKeepAccounts.size(); i++) {
            //添加到link表
            Integer isignseq = 0;
            switch (accKeepAccounts.get(0).getBusiType()) {
                case "310":
                    isignseq = 4;
                    break;
                case "311":
                    isignseq = 2;
                    break;
            }
            int no = addLink(null, accKeepAccounts.get(i), isignseq, accKeepAccounts.get(i).getFinanceCode(), null);
            if (no == 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "添加到数据库时数据出现问题");
            }
        }
        for (int i = 0; i < tempList.size(); i++) {
            BigDecimal payBuildAmount = BigDecimal.ZERO;
            for (int j = 0; j < accKeepAccounts.size(); j++) {
                if (tempList.get(i).equals(accKeepAccounts.get(j).getFinanceCode())) {
                    payBuildAmount = payBuildAmount.add(accKeepAccounts.get(j).getPayAmount());
                }
            }
            Map<String, Object> mapTwo = new HashMap<>(8);
            mapTwo.put("num", i + 2);
            mapTwo.put("ccode", accKeepAccounts.get(i).getFinanceCode());
            mapTwo.put("amount", payBuildAmount);
            if (("310").equals(type)) {
                nextMap = map(mapTwo);
            } else {
                nextMap = mapDep(mapTwo);
            }
            list.add(i + 1, nextMap);
        }
        return list;
    }

    /**
     * 查看自然幢是否有财务编号若有的话则加入没有的话  新建加入
     *
     * @param acc
     * @return
     */
    private AccKeepAccount addFinCode(AccKeepAccount acc, String buildId) {
        BaseBuildInfo baseBuildInfo = baseBuildInfoMapper.getInfo(buildId);
        //如果财务编号为空，则掉财务添加接口新增财务编号
        if (StringUtils.isBlank(baseBuildInfo.getFinanceCode())) {
            BaseBuildInfo base = baseBuildInfoService.addBuild(baseBuildInfo);
            int num = baseBuildInfoMapper.updateFineNo(base.getId(), base.getFinanceCode());
            if (num == 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "自然幢的财务编号生成失败");
            }
            acc.setFinanceCode(base.getFinanceCode());
        } else {
            //否则直接存入到keep表
            acc.setFinanceCode(baseBuildInfo.getFinanceCode());
        }
        return acc;
    }


    public List<Map<String, Object>> addaccVouch(List<AccKeepAccount> accKeepAccounts) {
        //是否汇总记账0否1是
        String code = sysCoreParamMapper.getParamValueByCode("56");
        //310退款  311交存312支用
        //若为退款会存在一个自然幢则直接查出他的财务编号
        if (accKeepAccounts.get(0).getBusiType().equals("310")) {
            for (AccKeepAccount acc : accKeepAccounts) {
                String buildId = "";
                String houseId = accTransactionLogMapper.selectByBusNo(acc.getBusiNo()).get(0).getHouseId();
                buildId = baseHouseInfoMapper.getInfo(houseId).getBuildNo();
                addFinCode(acc, buildId);
            }
        }
        //若果为非汇总
        if ((NumStrEnum.ZERO.getNum()).equals(code)) {
            switch (accKeepAccounts.get(0).getBusiType()) {
                case "310":
                    for (int i = 0; i < accKeepAccounts.size(); i++) {
                        //添加到财务
                        List<AccKeepAccount> keepAccounts = new ArrayList<>();
                        keepAccounts.add(accKeepAccounts.get(i));
                        addFinanceDepReq(keepAccounts, accKeepAccounts.get(0).getPayAmount());
                    }
                    break;
                case "311":
                    for (int i = 0; i < accKeepAccounts.size(); i++) {
                        List<AccKeepAccount> keepAccounts = new ArrayList<>();
                        keepAccounts.add(accKeepAccounts.get(i));
                        //若是缴存则可能是两个自然幢
                        for (AccKeepAccount acc : accKeepAccounts) {
                            List<AccKeepAccount> accBuild = accTransactionLogMapper.selectGroupByBuild(acc.getBusiNo());
                            for (AccKeepAccount a : accBuild) {
                                a.setBusiType("311");
                                a.setBankCode(accKeepAccounts.get(0).getBankCode());
                                a.setBusiNo(acc.getBusiNo());
                                addFinCode(a, a.getBuildId());
                            }
                            addFinanceDepReq(accBuild, accKeepAccounts.get(0).getPayAmount());
                        }
                    }
                    break;
                case "312":
                    for (int i = 0; i < accKeepAccounts.size(); i++) {
                        //添加财务
                        List<AccKeepAccount> keepAccounts = new ArrayList<>();
                        keepAccounts.add(accKeepAccounts.get(i));
                        if (accKeepAccounts.get(i).getPayAmount().compareTo(BigDecimal.ZERO) != 0) {
                            List<Map<String, Object>> list = addFinance(keepAccounts, accKeepAccounts.get(i).getPayAmount());
                            String num = connect(list, "http://192.168.31.101:8091/AccVouch/writeAccVouch");
                            if (num == null) {
                                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "传给财务数据库时数据出现问题");
                            }
                            if (accKeepAccounts.get(i).getPayAmount().compareTo(BigDecimal.ZERO) != 0) {
                                int no = accBusiVouchLinkMapper.updateInoid(num, accKeepAccounts.get(i).getBusiNo());
                                if (no <= 0) {
                                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "修改财务数据有问题");
                                }
                            }
                        }
                    }
                    break;
                default:
                    break;

            }//r若为汇总财务
        } else {
            switch (accKeepAccounts.get(0).getBusiType()) {
                case "310":
                    //肯定是同一银行
                    addAllDepReq(accKeepAccounts);
                    break;
                case "311":
                    addAllDepReq(accKeepAccounts);
                    break;
                case "312":
                    BigDecimal payAmounts = BigDecimal.ZERO;
                    List<AccKeepAccount> list = new ArrayList<>();
                    for (int i = 0; i < accKeepAccounts.size(); i++) {
                        list.add(accKeepAccounts.get(i));
                        payAmounts = payAmounts.add(accKeepAccounts.get(i).getPayAmount());
                    }
                    if (list.size() > 0 && payAmounts.compareTo(BigDecimal.ZERO) != 0) {
                        List<Map<String, Object>> lists = addFinance(list, payAmounts);
                        String num = connect(lists, "http://192.168.31.101:8091/AccVouch/writeAccVouch");
                        if (num == null) {
                            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "传给财务数据库时数据出现问题");
                        }
                        for (AccKeepAccount a : list) {
                            if (a.getPayAmount().compareTo(BigDecimal.ZERO) != 0) {
                                int no = accBusiVouchLinkMapper.updateInoid(num, a.getBusiNo());
                                if (no <= 0) {
                                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "修改财务数据有问题");
                                }
                            }
                        }
                    }
            }
        }
        return null;
    }

    /**
     * 汇总打印  缴存/退款
     */
    private void addAllDepReq(List<AccKeepAccount> accKeepAccounts) {
        BigDecimal pay = new BigDecimal(0);
        List<AccKeepAccount> keepAccounts = new ArrayList<>();
        String join = "";
        for (int i = 0; i < accKeepAccounts.size(); i++) {
            join = String.join(",", accKeepAccounts.get(i).getBusiNo());
            pay = pay.add(accKeepAccounts.get(i).getPayAmount());
        }
        List<AccKeepAccount> accBuild = accTransactionLogMapper.selectGroupByBuild(join);
        for (AccKeepAccount a : accBuild) {
            a.setBusiType(accKeepAccounts.get(0).getBusiType());
            a.setBankCode(accKeepAccounts.get(0).getBankCode());
            a.setBusiNo(accKeepAccounts.get(0).getBusiNo());
            addFinCode(a, a.getBuildId());
        }
        addFinanceDepReq(accBuild, accKeepAccounts.get(0).getPayAmount());
    }

    /**
     * 自然装
     */
    private String addBuildNo(BaseBuildInfo baseBuildInfo) {
        String ccode;
        if (StringUtils.isBlank(baseBuildInfo.getFinanceCode())) {
            BaseBuildInfo base = baseBuildInfoService.addBuild(baseBuildInfo);
            int num = baseBuildInfoMapper.updateFineNo(base.getId(), base.getFinanceCode());
            if (num == 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "自然幢的财务编号生成失败");
            } else {
                ccode = base.getFinanceCode();
            }
        } else {
            ccode = baseBuildInfo.getFinanceCode();
        }
        return ccode;
    }

    /**
     * 汇总 使用
     */
    private List<Map<String, Object>> addFinance(List<AccKeepAccount> accKeepAccounts, BigDecimal payAmounts) {
        List<Map<String, Object>> list = new ArrayList<>();
        //获取银行的科目代码
        String ccodeBank = ccodeBank(accKeepAccounts.get(0).getBankCode());
        Map<String, Object> map = new HashMap<>();
        map.put("num", 1);
        map.put("ccode", ccodeBank);
        map.put("amount", payAmounts);
        Map<String, Object> maps = mapExp(map);
        list.add(0, maps);
        //质保金是质保金，上一笔是上一笔
        //获取到项目编号
        String bus = "";
        for (AccKeepAccount acc : accKeepAccounts) {
            List<ExpPayReq> expPayReqss = expPayReqMapper.getByPayNo(acc.getBusiNo());
            List<ExpProjectReqDetail> expProjectReqDetails = expProjectReqDetailMapper.selectForPayReqIdByRooms(expPayReqss.get(0).getReqId());
            for (int j = 0; j < expProjectReqDetails.size(); j++) {
                String ccode = "";
                BigDecimal amount = expPayReqDetailMapper.selectSumByBuildId(expProjectReqDetails.get(j).getRooms(), expPayReqss.get(0).getId());
                if (amount.compareTo(BigDecimal.ZERO) == 0) {
                    continue;
                }
                BaseBuildInfo baseBuildInfo = baseBuildInfoMapper.getInfo(expProjectReqDetails.get(j).getBuildNo());
                //如果财务编号为空，则掉财务添加接口新增财务编号
                ccode = addBuildNo(baseBuildInfo);
                int no = addLink(null, acc, 3, ccode, amount);
                if (no == 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "添加到数据库时数据出现问题");
                }
            }
            bus = bus + "," + acc.getBusiNo();
        }
        bus = bus.substring(1);
        List<ExpPayReq> expPayReq = expPayReqMapper.getByPayNo(bus);
        //自然幢id   rooms
        String reqId = "";
        for (ExpPayReq e : expPayReq) {
            reqId = reqId + "," + e.getReqId();
        }
        String a = reqId.substring(1);
        List<ExpProjectReqDetail> expProjectReqDetails = expProjectReqDetailMapper.selectForPayReqIdByRooms(a);
        if (expProjectReqDetails == null) {
            return null;
        }
        //这自然幢的钱
        for (int j = 0; j < expProjectReqDetails.size(); j++) {
            String ccode;
            BigDecimal amount = BigDecimal.ZERO;
            for (ExpPayReq e : expPayReq) {
                amount = expPayReqDetailMapper.selectSumByBuildId(expProjectReqDetails.get(j).getRooms(), e.getId());
            }
            if (amount.compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            BaseBuildInfo baseBuildInfo = baseBuildInfoMapper.getInfo(expProjectReqDetails.get(j).getBuildNo());
            //如果财务编号为空，则掉财务添加接口新增财务编号
            ccode = addBuildNo(baseBuildInfo);
            Map<String, Object> mapTwo = new HashMap<>();
            mapTwo.put("num", (j + 2));
            mapTwo.put("ccode", ccode);
            mapTwo.put("amount", amount);
            list.add(j + 1, mapExp(mapTwo));
        }
        return list;
    }

    /**
     * 财务接口
     */
    public String connect(List<Map<String, Object>> list, String changUrl) {
        //新建一个客户对象
        CloseableHttpClient client = HttpClients.createDefault();
        // String url = "http://192.168.31.235:8090/AccVouch/writeAccVouch";
        //String url = "http://192.168.31.233:8081/baseBuildInfo/getInfo";
        String url = changUrl;
        HttpPost post = new HttpPost(url);
        //  对参数进行打包
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("accVouchs", list);
        post.setHeader("Content-Type", "application/json;charset=utf-8");
        post.addHeader("Authorization", "Basic YWRtaW46");
        //4.对打包好的参数，使用UrlEncodedFormEntity工具类生成实体的类型数据
        StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
        //5.将含有请求参数的实体对象放到post请求中
        post.setEntity(entity);
        //6.新建一个响应对象来接收客户端执行post的结果
        CloseableHttpResponse response = null;
        try {
            response = client.execute(post);
            return EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            log.error("IOException错误信息:()", e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("IOException错误信息:()", e.getMessage(), e);
                }
            }
        }
        return null;

    }


    /**
     * 查询bus的列表，并删除
     */
    private int del(AccKeepAccount accKeepAccount) {
        List<AccBusiVouchLink> accBusiVouchLinks = accBusiVouchLinkMapper.selectByBusiNo(accKeepAccount.getBusiNo());
        List<Map<String, Object>> list = new ArrayList<>();
        for (AccBusiVouchLink a : accBusiVouchLinks) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("baseName", sqlName());
            map.put("inoId", a.getInoId());
            map.put("ccode", a.getCcode());
            map.put("amount", a.getPayAmount());
            map.put("isignseq", a.getIsignseq());
            String mouth = a.getAccountPeriod();
            String strh = mouth.substring(mouth.length() - 2, mouth.length());
            map.put("iperiod", strh);
            list.add(map);
        }
        String num = connect(list, "http://192.168.31.101:8091/AccVouch/clearAccVouch");
        if (!num.equals(NumStrEnum.ONE.getNum())) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "冲正时删除财务数据库出现问题");
        }
        return accBusiVouchLinkMapper.deleteByBusiNo(accKeepAccount.getBusiNo());
    }

    /**
     * 核对,初始核对
     * CDG
     * 2019-07-31
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult check(String ids, String state, String arcType) {
        int num = 0;
        String[] idArr = ids.split(",");

        for (String id : idArr) {
            AccKeepAccount accKeepAccount = new AccKeepAccount();
            accKeepAccount.setId(id);
            accKeepAccount.setAccountState(state);
            AccKeepAccount a = accKeepAccountMapper.getInfo(id);
            if ((NumStrEnum.ONE.getNum()).equals(state)) {
                String sys = sysCoreParamMapper.getParamValueByCode("59");
                if (null != sys && sys.equals(NumStrEnum.ONE.getNum())) {
                    int no = del(a);
                    if (no < 0) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), "本地数据出现错误");
                    }
                }
                accKeepAccount.setCheckOper("");
                accKeepAccount.setCheckTime(null);

            } else {
                String busiType = a.getBusiType();
                if ("311".equals(busiType)) {
                    //缴存业务 校验图档
                    //校验图档必传项
                    CommonResult result = fileService.checkFile(id, arcType);
                    if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
                        return result;
                    }
                }
                accKeepAccount.setCheckTime(DateUtils.getDateNow());
                accKeepAccount.setCheckOper(ShiroUserUtil.getUserName());
            }
            num = accKeepAccountMapper.check(state, accKeepAccount.getCheckTime(), accKeepAccount.getCheckOper(), id);
            if (num == NumberEnum.ZERO.getNum()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
        }
        // 添加到财务
        if (state.equals(NumStrEnum.TWO.getNum())) {
            String sys = sysCoreParamMapper.getParamValueByCode("59");
            if (null != sys && sys.equals(NumStrEnum.ONE.getNum())) {
                String cc = addFin(ids);
                if (cc == null) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "财务数据错误");
                }
            }

        }
        return CommonResult.ResponseResult(num);
    }

    /**
     * 日终核对---批量结算查询收入支付 （金额，笔数）
     *
     * @param bankCode       银行id
     * @param tallyTimeStart 开始时间（结算时间）
     * @param tallyTimeEnd   结算时间（最大当天时间）
     * @return 返回  SettleAccounts 实体
     */
    @Override
    public SettleAccounts batchSettlementInquiry(String bankCode, String tallyTimeStart, String tallyTimeEnd) {

        return accKeepAccountMapper.batchSettlementInquiry(bankCode, tallyTimeStart, tallyTimeEnd);
    }

    /**
     * 冲正、记账里的退款
     */
    private int changereq(AccKeepAccount accKeepAccount, String accFrozeType, String funType) {
        String no = NumStrEnum.ZERO.getNum();
        String state = NumStrEnum.ONE.getNum();
        String ownerInfoState = NumStrEnum.ONE.getNum();
        String ownerState = NumStrEnum.ZERO.getNum();
        int num = NumberEnum.ZERO.getNum();
        List<RefReqList> reqList = refReqListMapper.getInfoByNo(accKeepAccount.getBusiNo());
        RefPayInfo refPayInfo = refPayInfoMapper.getInfoByPayNo(accKeepAccount.getBusiNo());
        RefReq refReq = refReqMapper.getInfo(refPayInfo.getReqId());
        if (funType.equals(NumStrEnum.ZERO.getNum())) {//如果是冲正，修改refPay状态
            num = refPayInfoMapper.updateState(refPayInfo.getId(), NumStrEnum.ONE.getNum(), NumStrEnum.FIVE.getNum(), null);
            if (num == NumberEnum.ZERO.getNum()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
            //查询有没有新建的
            List<RefPayInfo> refPayInfos = refPayInfoMapper.selectAllPayNo(refReq.getId(), NumStrEnum.FOUR.getNum());
            if (refPayInfos.size() <= 1) {
                num = refReqMapper.updateStep(refReq.getId(), NumStrEnum.THREE.getNum());
                if (num == NumberEnum.ZERO.getNum()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                }
            }
        }
        List<BaseHouseInfo> list = new ArrayList<>();
        for (RefReqList item : reqList) {
            num = listUpdate(item, item.getPayAmount(), Integer.parseInt(funType), accFrozeType, funType);
            list.add(baseHouseInfoMapper.getInfo(item.getHouseId()));
            if (num == NumberEnum.ZERO.getNum()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
        }
        //修改业主状态
        for (BaseHouseInfo baseHouseInfo : list) {
            List<BaseOwnerInfo> baseOwnerInfos;
            //冲正
            if ((NumStrEnum.ZERO.getNum()).equals(funType)) {
                //225销户226部分退款227全额退款
                //状态 0 空房 1 已售 2销户  3待销户  4待退房
                List<BaseOwnerInfo> baseOwnerInfo = baseOwnerInfoMapper.getInfoListByHouseIdDelNow(baseHouseInfo.getId());
                if ("225".equals(refReq.getRefType())) {
                    state = NumStrEnum.THREE.getNum();
                    ownerState = NumStrEnum.ONE.getNum();
                    no = "close_account";
                    if (0 != baseOwnerInfo.size()) {
                        String owenrNo = baseOwnerInfoMapper.selectByOwnerNo(baseHouseInfo.getId());
                        num = baseOwnerInfoMapper.updatStateByOwnerNo(owenrNo);
                    }
                } else if ("227".equals(refReq.getRefType())) {
                    state = NumStrEnum.FOUR.getNum();
                    ownerState = NumStrEnum.ONE.getNum();
                    no = "ref_req";
                    if (0 != baseOwnerInfo.size()) {
                        String owenrNo = baseOwnerInfoMapper.selectByOwnerNo(baseHouseInfo.getId());
                        num = baseOwnerInfoMapper.updatStateByOwnerNo(owenrNo);
                    }
                } else if ("226".equals(refReq.getRefType())) {
                    ownerState = NumStrEnum.ONE.getNum();
                    no = "ref_req";
                }
            } else {//记账
                if ("225".equals(refReq.getRefType()) || "227".equals(refReq.getRefType())) {
                    List<BaseOwnerInfo> base;
                    base = baseOwnerInfoMapper.selectOwnerByState(baseHouseInfo.getId(), NumStrEnum.THREE.getNum());
                    if (base.size() != 0) {
                        for (BaseOwnerInfo b : base) {
                            int a = baseOwnerInfoMapper.updatState(NumStrEnum.ZERO.getNum(), b.getId(), NumStrEnum.THREE.getNum());
                            if (a == 0) {
                                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "修改原业主状态报错");
                            }
                        }
                    }
                }
                //修改状态为未交
                //baseHouseInfoMapper.changeDueState(baseHouseInfo.getId(), NumStrEnum.FOUR.getNum());
                baseOwnerInfos = baseOwnerInfoMapper.getInfoListByHouseIdAll(baseHouseInfo.getId());
                //225销户226部分退款227全额退款
                if ("225".equals(refReq.getRefType())) {
                    state = NumStrEnum.TWO.getNum();
                    ownerInfoState = NumStrEnum.FOUR.getNum();
                    ownerState = NumStrEnum.ZERO.getNum();
                    if (0 != baseOwnerInfos.size()) {
                        for (BaseOwnerInfo b : baseOwnerInfos) {
                            num = baseOwnerInfoMapper.updatState(ownerInfoState, b.getId(), NumStrEnum.ONE.getNum());
                        }
                    }
                } else if ("227".equals(refReq.getRefType())) {
                    state = NumStrEnum.ZERO.getNum();
                    ownerInfoState = NumStrEnum.FOUR.getNum();
                    ownerState = NumStrEnum.ZERO.getNum();
                    if (0 != baseOwnerInfos.size()) {
                        for (BaseOwnerInfo b : baseOwnerInfos) {
                            num = baseOwnerInfoMapper.updatState(ownerInfoState, b.getId(), NumStrEnum.ONE.getNum());
                        }
                    }
                } else if ("226".equals(refReq.getRefType())) {
                    ownerState = NumStrEnum.ONE.getNum();
                }
                no = NumStrEnum.ZERO.getNum();
            }
            baseHouseInfo.setState(state);
            baseHouseInfo.setFlowInProgress(no);
            baseHouseInfo.setOwnerState(ownerState);
            num = baseHouseInfoMapper.update(baseHouseInfo);
            if (num == NumberEnum.ZERO.getNum()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
        }
        if ("225".equals(refReq.getRefType()) || "227".equals(refReq.getRefType())) {
            if (!funType.equals(NumStrEnum.ONE.getNum())) {
                //冲正修改log的状态,把这个业主数据改为有效
                for (RefReqList refReqList : reqList) {
                    BaseOwnerInfo baseOwnerInfo = baseOwnerInfoMapper.getInfoByAccNoOwner(refReqList.getHouseId());
                    accTransactionLogMapper.updateIsEffectiveOnwerId(baseOwnerInfo.getId());
                }
            }
        }
        return num;
    }

    /**
     * @param bankCode       银行id
     * @param tallyTimeStart 开始时间（结算时间）
     * @param tallyTimeEnd   结算时间（最大当天时间）
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult settlement(String bankCode, String tallyTimeStart, String tallyTimeEnd) {
        //若为空则说明是单独结算，需要核对
        if (StringUtils.isBlank(tallyTimeStart)) {
            int no = accKeepAccountMapper.selectNotByAcc(bankCode, tallyTimeEnd);
            if (no > 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "有数据未核对，请核对之后结算！");
            }
        }
        //更改数据的银行表后面的最后结算日期字段
        int updateNum = baseContractorBankInfoMapper.updateSettlementTime(bankCode, tallyTimeEnd);
        if (updateNum <= 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        if (StringUtils.isNotBlank(tallyTimeStart)) {
            String sys = sysCoreParamMapper.getParamValueByCode("59");
            if (null == sys) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "请去参数设计是否调用财务接口");
            }
            if (sys.equals(NumStrEnum.ONE.getNum())) {
                List<AccKeepAccount> deps = accKeepAccountMapper.selectByBusi(bankCode, tallyTimeStart, tallyTimeEnd, "311");
                List<AccKeepAccount> reqs = accKeepAccountMapper.selectByBusi(bankCode, tallyTimeStart, tallyTimeEnd, "310");
                List<AccKeepAccount> exps = accKeepAccountMapper.selectByBusi(bankCode, tallyTimeStart, tallyTimeEnd, "312");
                if (deps.size() != 0) {
                    addaccVouch(deps);
                }
                if (reqs.size() != 0) {
                    addaccVouch(reqs);
                }
                if (exps.size() != 0) {
                    addaccVouch(exps);
                }
            }
        }
        //如果是空就是单独结算
        if (StringUtils.isBlank(tallyTimeStart)) {
            int aa = accKeepAccountMapper.selectNotByAcc(bankCode, tallyTimeEnd);
            if (aa > 0) {
                int num = accKeepAccountMapper.settlement(bankCode, tallyTimeStart, tallyTimeEnd);
                if (num == 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "操作失败");
                }
            }
        } else {
            int a = accKeepAccountMapper.selectByAcc(bankCode, tallyTimeEnd);
            if (a > 0) {
                int num = accKeepAccountMapper.settlement(bankCode, tallyTimeStart, tallyTimeEnd);
                if (num == 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "操作失败");
                }
            }
        }
        return CommonResult.ResponseResult(updateNum);
    }
}